const path = '/static/js/xlsxWorker.js'
export function getOutputWorker (headers, tableData, isRangeMode, mergeVal) {
  try {
    const worker = new Worker(path) // 创建worker对象
    worker.postMessage({
      headers,
      tableData,
      isRangeMode,
      mergeVal
    })
    return new Promise((resolve) => {
      worker.onmessage = ({ data: blob }) => {
        resolve(blob)
        worker.terminate()
      }
    })
  } catch (error) {
    console.error(error)
  }
}

export class ExportExcel {
  constructor (headers, tableData, mergeVal) {
    this.headers = headers
    this.tableData = tableData
    this.mergeVal = mergeVal
  }

  async toExport (fileName) {
    const blob = await getOutputWorker(this.headers, this.tableData, false, this.mergeVal)
    if (window.navigator?.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob, 'out.xlsx')
    } else {
      var url = window.URL.createObjectURL(blob)
      var a = document.createElement('a')
      a.href = url
      a.download = (fileName || 'download') + '.xlsx'
      a.click()
      window.URL.revokeObjectURL(url)
    }
  }
}

export function downLoad (headers, tableData, fileName) {
  getOutputWorker(headers, tableData, fileName).then((blob) => {
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveOrOpenBlob(blob, 'out.xlsx')
    } else {
      var url = window.URL.createObjectURL(blob)
      var a = document.createElement('a')
      a.href = url
      a.download = (fileName || 'download') + '.xlsx'
      a.click()
      window.URL.revokeObjectURL(url)
    }
  })
}
